package com.sunchangming.stmdb.xgen;

public class TypeMap extends Type {

	@Override
	public String getName(Variable variable) {
		return "java.util.HashMap<" + variable.getKeyType().getBoxName() + "," + variable.getValueType().getBoxName()
				+ ">";
	}

	@Override
	public String getBoxName() {
		return null;
	}

	@Override
	public String getMarshalStr(Variable v, String osname) {
		final StringBuilder sb = new StringBuilder();
		sb.append(osname).append(".writeInt(").append(v.getName()).append(".size());\n");
		sb.append("for(java.util.Map.Entry<").append(v.getKeyType().getBoxName()).append(",")
				.append(v.getValueType().getBoxName()).append("> e:").append(v.getName()).append(".entrySet()){\n");
		final Variable lk = new Variable("_k_", v.getKeyType());
		final Variable lv = new Variable("_v_", v.getValueType());
		sb.append(v.getKeyType().getName(lk)).append(" _k_=e.getKey();\n");
		sb.append(v.getValueType().getName(lv)).append(" _v_=e.getValue();\n");
		sb.append(lk.getMarshalStr()).append(";\n");
		sb.append(lv.getMarshalStr()).append(";\n");
		sb.append("}");
		return sb.toString();
	}

	@Override
	public String getUnmarshalStr(Variable v, String osname, boolean useThis) {
		final StringBuilder sb = new StringBuilder();
		sb.append("this." + v.getName() + "=new " + this.getName(v) + "();\n");
		sb.append("for(int i=").append(osname).append(".readInt();i!=0;--i){\n");
		final Variable lk = new Variable("_k_", v.getKeyType());
		final Variable lv = new Variable("_v_", v.getValueType());
		sb.append(lk.getMainType().getBoxName()).append(" ").append(lk.getLocalUnmarshalStr()).append(";\n");
		sb.append(lv.getMainType().getBoxName()).append(" ").append(lv.getLocalUnmarshalStr()).append(";\n");
		sb.append("this.").append(v.getName()).append(".put(_k_,_v_);\n");
		sb.append("}");
		return sb.toString();
	}

	@Override
	public String getDefaultValue(Variable variable) {
		return "new " + getName(variable) + "()";
	}

	@Override
	public String getHashCodeStr(Variable variable) {
		return "this." + variable.getName() + ".hashCode()";
	}

}
